package leetcode;
/*
   思路：
   1、简单粗暴
   遍历haystack，如果当前字母和needle的首字母相同，那么继续比较双方的下一个字母。
   2、参见String.indexof(String)

 */
public class Code28 {
    public static int strStr(String haystack, String needle) {
        int hLength = haystack.length();
        int nLength = needle.length();

        if(hLength < nLength){
            return -1;
        }

        int nextIndex = -1;
        char nFirst = needle.charAt(0);
        int i=0;
        int maxIndex = hLength -nLength +1;
        while (i < maxIndex){
            char hCur = haystack.charAt(i);
            if(hCur == nFirst){
                int j=1;
                for(;j<nLength && i+j < hLength;j++){
                    char hc = haystack.charAt(i + j);
                    char nc = needle.charAt(j);
                    if(hc == nFirst && i > nextIndex){
                        nextIndex = i+j;
                    }

                    if(hc != nc){
                        break;
                    }
                }
                if(j == nLength){
                    return i;
                }
                if(nextIndex > i) {
                    i = nextIndex;
                }else{
                    i++;
                }
            }else {
                i++;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int i = strStr("mississippi", "issip");
        System.out.println(i);
    }
}
